from django.shortcuts import render
from django.contrib.auth import login
from django.contrib.auth import authenticate
from django.contrib.auth import logout
from django.shortcuts import redirect
from django.urls import reverse
from django.contrib.auth.decorators import login_required

from common_libs.authentication.auth import check_password
from .forms import PasswordResetForm

# Create your views here.

def account_login(request):
    '''登录页面'''
    if request.method == 'GET':
        error_msg = ''
    elif request.method == 'POST':
        email = request.POST.get('email')
        password = request.POST.get('password')
        user_obj = check_password(username=email, password=password)    # 验证用户名和密码
        if user_obj:
            login(request, user_obj)    # 登录
            url = request.GET.get('next','/')
            return redirect(url)
        else:
            error_msg = '用户名或密码错误'


    return render(request, 'login.html',{'error_msg': error_msg})


def account_logout(request):
    '''登出'''
    user = getattr(request, 'user', None)
    logout(request)    # 登出
    url = reverse('login')
    return redirect(url)


@login_required
def password_reset(request):
    '''修改密码'''
    if request.method == 'GET':
        form_obj = PasswordResetForm()
    elif request.method == 'POST':
        form_obj = PasswordResetForm(request.POST)
        if form_obj.is_valid():
            password = form_obj.cleaned_data['password1']
            request.user.set_password(password)
            request.user.save()
            return redirect('/')

    return render(request,'password_reset.html',{'form_obj': form_obj})


@login_required
def index(request):
    '''首页'''
    return render(request, 'index.html')